package com.CMC.yhdeng;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.CMC.yhdeng.ExamUnitContent.ExamType;
import com.CMC.yhdeng.QuizBaseActivity.QuizMode;

public class QuizTypeSelection extends Activity {

	QuizMode quizType=QuizMode.QM_Unknow;
	ArrayList<BookContent> datas;
	int currentBook=0;
	Spinner sp1,sp2,sp3, sp4;
	boolean isDataLoad=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent it= getIntent();
		String stype=getString(R.string.intent_type);
		quizType=(QuizMode) it.getExtras().get(stype);
		
		if(quizType==QuizMode.QM_Practice) setContentView(R.layout.activity_quiz_type_selection);
		else if(quizType==QuizMode.QM_Test) setContentView(R.layout.activity_quiz_type_selection_p);
		
		
//		if(quizType>0)
//		{
//			Button btn=(Button)findViewById(R.id.btnWord2KK);
//			btn.setBackgroundResource(R.drawable.p_btn_01);
//			
//			btn=(Button)findViewById(R.id.btnKK2Word);
//			btn.setBackgroundResource(R.drawable.p_btn_02);
//			
//			btn=(Button)findViewById(R.id.btnSound2Word);
//			btn.setBackgroundResource(R.drawable.p_btn_03);
//			
//			btn=(Button)findViewById(R.id.btnWord2Sound);
//			btn.setBackgroundResource(R.drawable.p_btn_04);
//			
//			btn=(Button)findViewById(R.id.btnKK2SOUND);
//			btn.setBackgroundResource(R.drawable.p_btn_05);
//			
//			View iv=findViewById(R.id.llytBottomTools);
//			iv.setBackgroundResource(R.drawable.p_keybtn_bg);
//		}
		
		View v=findViewById(R.id.include_spin_row1);
		TextView tv=(TextView)v.findViewById(R.id.txtChapterTitle);
		sp1=(Spinner)v.findViewById(R.id.spinner1);
		tv.setTextColor(getResources().getColor(R.color.quiz_type_selection_text_color) );
		tv.setText(R.string.quiz_type_selection_tv1);
		sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int pos, long arg3) {
				if(currentBook!=pos)
				{
					changeBook(pos);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		
		v=findViewById(R.id.include_spin_row2);
		tv=(TextView)v.findViewById(R.id.txtChapterTitle);
		sp2=(Spinner)v.findViewById(R.id.spinner1);
		tv.setTextColor(getResources().getColor(R.color.quiz_type_selection_text_color) );
		tv.setText(R.string.quiz_type_selection_tv2);
		sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int pos, long arg3) {
				BookContent bc=getCurrentBook();
				if(pos!=bc.getCurrent())
				{
					changeChapter(pos);
				}
				
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		v=findViewById(R.id.include_spin_row3);
		tv=(TextView)v.findViewById(R.id.txtChapterTitle);
		sp3=(Spinner)v.findViewById(R.id.spinner1);
		tv.setTextColor(getResources().getColor(R.color.quiz_type_selection_text_color) );
		tv.setText(R.string.quiz_type_selection_tv3);
		sp3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				changeUnit(arg2);
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		v=findViewById(R.id.include_spin_row4);
		tv=(TextView)v.findViewById(R.id.txtChapterTitle);
		sp4=(Spinner)v.findViewById(R.id.spinner1);
		tv.setTextColor(getResources().getColor(R.color.quiz_type_selection_text_color) );
		tv.setText(R.string.quiz_type_selection_tv4);
		sp4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				
				changeExam(arg2);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
	}

	private void changeBook(int idx)
	{
		currentBook=idx;
		if(getCurrentBook().objs.size()==0)
		{
			sp2.setAdapter(null);
			sp3.setAdapter(null);
			sp4.setAdapter(null);
			disableAllButton();
			return;
		}
		changeChapter(-1);
	}
	private void changeChapter(int idx)
	{
		BookContent bc=getCurrentBook();
		sp3.setAdapter(null);
		if(bc.objs.size()==0)
		{
			sp3.setAdapter(null);
			sp4.setAdapter(null);
			disableAllButton();
			return;
		}
		if(idx==-1)
		{
			setListForSpinner(sp2, bc.objs);
			idx=0;
			sp2.setSelection(idx);
		}
		bc.setCurrent(idx);
		changeUnit(-1);
	}
	private void changeUnit(int idx)
	{
		ChapterContent ch=getCurrentChapter();
		
		if(ch.objs.size()==0)
		{
			sp4.setAdapter(null);
			disableAllButton();
			return;
		}
		if(idx==-1)
		{//change all unit by new chapter
			setListForSpinner(sp3, ch.objs);
			idx=0;
			sp3.setSelection(idx);
		}
		ch.setCurrent(idx);
		
		changeExam(-1);
//		filterQuizTypeButtonWithList(ch.getCurrentUnit().objs);
		
	}
	private void changeExam(int idx)
	{
		UnitContent uc=getCurrentUnitContent();
		if(uc.objs.size()==0)
		{
			disableAllButton();
			return;
		}
		
		if(idx==-1)
		{
			setListForSpinner(sp4, uc.objs);
			idx=0;
			sp4.setSelection(idx);
		}
		uc.setCurrent(idx);
		
		filterQuizTypeButtonWithList(uc.getCurObj());
	}
	private HashMap<ExamType, View> makeButtonCollection()
	{
		HashMap<ExamType, View> map=new HashMap<ExamUnitContent.ExamType, View>();
		map.put(ExamType.KK2SOUND, findViewById(R.id.btnKK2SOUND));
		map.put(ExamType.KK2WORD, findViewById(R.id.btnKK2Word));
		map.put(ExamType.SOUND2WORD, findViewById(R.id.btnSound2Word));
		map.put(ExamType.WORD2KK, findViewById(R.id.btnWord2KK));
		map.put(ExamType.WORD2SOUND, findViewById(R.id.btnWord2Sound));
		return map;
	}
	private void disableAllButton()
	{
		HashMap<ExamType, View> map=makeButtonCollection();
		
		Collection<View> views=map.values();
		for (View view : views) {
			Button btn=(Button)view;
			btn.setEnabled(false);
		}
	}
	private void filterQuizTypeButtonWithList(ExamUnitContent euc)
	{
//		if(lst==null || lst.size()==0)return;
//		HashSet<ExamType> set=new HashSet<ExamUnitContent.ExamType>();
//
//		List<ExamUnitContent> l=(List<ExamUnitContent>)lst;
//		for (ExamUnitContent examUnitContent : l) {
//			set.add(examUnitContent.type);
//		}
		
		HashMap<ExamType, View> map=makeButtonCollection();
		Collection<View> collV=map.values();
		for (View view : collV) {
			view.setVisibility(View.INVISIBLE);
		}
		ExamType[] types= ExamType.values();
		for (ExamType examType : types) {
			Button btn=(Button) map.get(examType);
			if(euc.type== examType)
			{
				btn.setVisibility(View.VISIBLE);
				break;
			}
		}
	}
	private BookContent getCurrentBook()
	{
		return datas.get(currentBook);
	}
	private ChapterContent getCurrentChapter()
	{
		return getCurrentBook().getCurrentChapter();
	}
	
	private UnitContent getCurrentUnitContent()
	{
		return getCurrentChapter().getCurrentUnit();
	}
	private ExamUnitContent getCurrentExam()
	{
		return getCurrentUnitContent().getCurObj();
	}
	private Boolean setListForSpinner(Spinner sp, List lst)
	{
		if(lst.size()==0)return false;
		String[] strs=new String[lst.size()];
		int i=0;
		List<UnitBase> ulist=(List<UnitBase>)lst;
		for (UnitBase obj : ulist) {
			strs[i++]=obj.title;
		}
		
		ArrayAdapter<String> ada=new ArrayAdapter<String>(this, 
				R.layout.qts_spinner, strs);
//		ada.setDropDownViewResource(R.layout.qts_spinner);
		sp.setAdapter(ada);
		return true;
	}
	public void onButtonClick(View v)
	{
		String objName=getResources().getString(R.string.quiz_type_serializable);
		String quizTypeExtraTag=getResources().getString(R.string.quiz_type_extra_tag);
		Intent intent=null;
		switch(v.getId())
		{
		case R.id.btnWord2KK:
			intent = new Intent(this, Word2KKAct.class);
			break;
		case R.id.btnKK2Word:
			intent = new Intent(this, KK2Word.class);
			break;
		case R.id.btnSound2Word:
			intent = new Intent(this, Sound2wordActivity.class);
			
			break;
		case R.id.btnKK2SOUND:
			intent=new Intent(this, KK2SoundActivity.class);
			break;
		case R.id.btnWord2Sound:
			intent=new Intent(this, Word2soundActivity.class);
			break;
		default:
			return;
		}
		intent.putExtra(objName, getCurrentExam());
		intent.putExtra(quizTypeExtraTag, quizType);
	    startActivity(intent);
	}

	public String convertStreamToString(InputStream is) throws IOException {
		//
		// To convert the InputStream to String we use the
		// Reader.read(char[] buffer) method. We iterate until the
		// Reader return -1 which means there's no more data to
		// read. We use the StringWriter class to produce the string.
		//
		if (is != null) {
			Writer writer = new StringWriter();

			char[] buffer = new char[1024];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(is,
						"UTF-8"));
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				is.close();
			}
			return writer.toString();
		} else {
			return "";
		}
	}
	private List<BookContent> downloadUrl(String myurl) throws IOException {
		InputStream is = null;
		try {
			URL url = new URL(myurl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(10000 /* milliseconds */);
			conn.setConnectTimeout(15000 /* milliseconds */);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			// Starts the query
			conn.connect();
			int response = conn.getResponseCode();
			Log.d("debug", "The response is: " + response);
			is = conn.getInputStream();

			return readJsonStream(is);
			

		} finally {
			// Makes sure that the InputStream is closed after the app is
			// finished using it.
			if (is != null) {
				is.close();
			}
		}
	}
	
	public  List<BookContent> readJsonStream(InputStream in) throws IOException 
	{
//		Log.d("debug",in.toString());
	     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
//	     try {
	    	 //read book array
	 		reader.beginArray();
	 		ArrayList<com.CMC.yhdeng.BookContent> lst=new ArrayList<com.CMC.yhdeng.BookContent>();
	 		while (reader.hasNext()) {// read a book
	 			
	 			com.CMC.yhdeng.BookContent book=new com.CMC.yhdeng.BookContent();
	 			book.read(reader);
	 			Log.d("readJsonStream", book.title);
	 			lst.add(book);
	 			
	 		}
			reader.endArray();
			
//			reader.close();
			return lst;

	   }
	
//	public BookContent readJsonStream(InputStream in) throws IOException 
//	{
//		Log.d("debug",in.toString());
//	     JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
//	     try {
//	       return readBookContent(reader);
//	     } finally {
//	       reader.close();
//	     }
//	   }

	
//	   public BookContent readBookContent(JsonReader reader) throws IOException {
//	     BookContent bc=new BookContent();
//	    
//	     reader.beginObject();
//	     String tagName=reader.nextName();
//	     if(tagName.equals("book_id")==true)
//	     {
//	    	 bc.id= reader.nextString();
//	     }
//	     
//	     tagName=reader.nextName();
//	     if(tagName.equals("book_title")==true)
//	     {
//	    	 bc.title= reader.nextString();
//	     }
//	     
//	     tagName=reader.nextName();
//	     if(tagName.equals("books_content"))
//	     {
//	     reader.beginArray();
//	     while (reader.hasNext()) {
//	       bc.add(readChapter(reader));
//	     }
//	     reader.endArray();
//	     }
//	     reader.endObject();
//	     return bc;
//	   }
//	   public ChapterContent readChapter(JsonReader reader) throws IOException {
//
//		   ChapterContent di=new ChapterContent();
//		   
//		     reader.beginObject();
//		     while (reader.hasNext()) {
//		       String name = reader.nextName();
//		       String sRes=String.format("pre-fix tag=%s", name);
//		       Log.d("debug", sRes);
////		       if (name.equals("id")) {
//		    	 String s=reader.nextString();
//		    	 Log.d("debug", s);
////		         di.id =Long.getLong(s);
////		       } 
//		     }
//		     reader.endObject();
//		     return di;
//		   }


	@Override
	protected void onStart() {
		super.onStart();
		if(isDataLoad) return;
		isDataLoad=true;
		// get data from web
		String stringUrl = "http://www.urjotter.com/apis/exam/getExamList";
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			new AsyncTask<String, Void, List<BookContent>>() {

				@Override
				protected List<BookContent> doInBackground(String... params) {
					try {
						String s = params[0];
						return downloadUrl(s);
						
					} catch (IOException e) {
						Log.d("debug", e.getMessage());
						return null;
					}
				}

				@Override
				protected void onPostExecute(List<BookContent> result) {

					datas=(ArrayList<BookContent>) result;
					setListForSpinner(sp1, result);
					
					int sel=0;
					sp1.setSelection(sel);
					changeBook(sel);
					
					sel=0;
					sp2.setSelection(sel);
					changeChapter(sel);
					
					sel=1;
					sp3.setSelection(sel);
					changeUnit(sel);

					new AsyncTask<String, Void, List>(){

						@Override
						protected List doInBackground(String... params) {
							try {
								
								return  HistoryActivity.getScoreList("john");
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							return null;
						}

						@Override
						protected void onPostExecute(List result) {
							List<ScoreData> lst=(List<ScoreData>)result;
							if(lst.size()>0)
							{
								ScoreData a=lst.get(0);
								TextView tv=(TextView)findViewById(R.id.tvLastQuizRecord);
								String s=String.format("最近一次練習或測驗, %s, %s,\n測驗時間：%s,\n分數：%s", 
										a.book_name,a.exam_name, a.finsih_datetime, a.score);
								tv.setText(s);
							}
							
						}
						
						
					}.execute("");

					super.onPostExecute(result);
				}

			}.execute(stringUrl);
		} else {
			// textView.setText("No network connection available.");
		}
	}


	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

}
